package com.jhgsys.internal.peccancy.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jhgsys.internal.common.annotation.Log;
import com.jhgsys.internal.common.controller.BaseController;
import com.jhgsys.internal.common.entity.FebsConstant;
import com.jhgsys.internal.common.entity.FebsResponse;
import com.jhgsys.internal.common.entity.QueryRequest;
import com.jhgsys.internal.common.exception.FebsException;
import com.jhgsys.internal.common.utils.FebsUtil;
import com.jhgsys.internal.peccancy.constant.PeccancyConstant;
import com.jhgsys.internal.peccancy.dto.PeccancyAuditRecordDto;
import com.jhgsys.internal.peccancy.dto.PeccancyInformationDto;
import com.jhgsys.internal.peccancy.dto.PeccancyInformationQueryDto;
import com.jhgsys.internal.peccancy.entity.PeccancyClause;
import com.jhgsys.internal.peccancy.entity.PeccancyInformation;
import com.jhgsys.internal.peccancy.service.IPeccancyAuditRecordService;
import com.jhgsys.internal.peccancy.service.IPeccancyInformationService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.*;

/**
 * 违章罚款
 *
 * @author Wanghw
 * @date 2024-08-14 10:38:38
 */
@Slf4j
@Validated
@Controller
public class PeccancyChargeRecordController extends BaseController {

    @Autowired
    private IPeccancyAuditRecordService peccancyAuditRecordService;

    @Autowired
    private IPeccancyInformationService peccancyInformationService;

    @GetMapping(FebsConstant.VIEW_PREFIX + "peccancyChargeRecord")
    @RequiresPermissions("peccancyChargeRecord:view")
    public String peccancyAuditRecordIndex(Model model){
        model.addAttribute("hasHeadCompanyRole", hasHeadCompanyRole());
        model.addAttribute("tenantList",getTenantList());
        model.addAttribute("currentTenantId", getCurrentTenantId());
        return jumpPage("peccancy/peccancyChargeRecord/peccancyChargeRecordList");
    }

    /**
     * 跳转微信支付
     * @param model
     * @param id
     * @return
     * @throws JsonProcessingException
     */
    @GetMapping(FebsConstant.VIEW_PREFIX + "peccancyChargeRecord/offLine/{id}")
    @RequiresPermissions("peccancyChargeRecord:charge")
    public String peccancyChargeoffLine(Model model, @PathVariable("id") String id) {
        model.addAttribute("chargeUser",getCurrentUser());
        return jumpPage("peccancy/peccancyChargeRecord/peccancyChargeOffline");
    }

    /**
     * 跳转微信支付
     * @param model
     * @param id
     * @return
     * @throws JsonProcessingException
     */
    @GetMapping(FebsConstant.VIEW_PREFIX + "peccancyChargeRecord/wxpay/{id}")
    @RequiresPermissions("peccancyChargeRecord:charge")
    public String peccancyChargeWxPay(Model model, @PathVariable("id") String id) throws JsonProcessingException {
        PeccancyInformationDto dto = peccancyInformationService.findPeccancyInformationDtoById(id);
        model.addAttribute("peccancyInformation", JSON.parse(new ObjectMapper().writeValueAsString(dto)));
        return jumpPage("peccancy/peccancyChargeRecord/peccancyChargeRecordEdit");
    }



    /**
     * 审核查询（分页）
     * @author Wanghw
     * @date 2024-08-14 10:38:38
     */
    @GetMapping("peccancyChargeRecord/list")
    @ResponseBody
    @RequiresPermissions("peccancyChargeRecord:view")
    public FebsResponse peccancyChargeRecordList(QueryRequest request,
                                                @RequestParam(name = "startDate",required = true) @DateTimeFormat(pattern = "yyyy-MM-dd") Date startDate,
                                                @RequestParam(name = "endDate",required = true) @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate,
                                                @RequestParam(name = "projectName",required = false) String projectName,
                                                @RequestParam(name = "peccancyRealName",required = false) String peccancyRealName,
                                                @RequestParam(name = "penaltyAmountStatus",required = true) String penaltyAmountStatus,
                                                @RequestParam(name = "tenantId",required = true) String tenantId) {
        PeccancyInformationQueryDto peccancyInformation = new PeccancyInformationQueryDto();
        if(StringUtils.isNotBlank(projectName)){
            peccancyInformation.setProjectName(projectName);
        }
        if(StringUtils.isNotBlank(peccancyRealName)){
            peccancyInformation.setPeccancyRealName(peccancyRealName);
        }
        peccancyInformation.setStartDate(startDate);
        peccancyInformation.setEndDate(endDate);
        peccancyInformation.setTenantId(tenantId);
        peccancyInformation.setPenaltyAmountStatus(penaltyAmountStatus);
        StringJoiner joiner = new StringJoiner(StringPool.COMMA);
        joiner.add(PeccancyConstant.INFORMATION_STATUS.WAITING_AUDIT)
                .add(PeccancyConstant.INFORMATION_STATUS.AUDIT_FAIL)
                .add(PeccancyConstant.INFORMATION_STATUS.WAITING_ISSUANCE)
                .add(PeccancyConstant.INFORMATION_STATUS.ISSUANCE_FAIL)
                .add(PeccancyConstant.INFORMATION_STATUS.ISSUANCED);
        peccancyInformation.setStatus(joiner.toString());
        Map<String, Object> dataTable = getDataTable(this.peccancyInformationService.findPeccancyInformationDtoPage(request, peccancyInformation));
        return new FebsResponse().success().data(dataTable);
    }


    /**
     * 线下缴费
     * @author admin
     * @date 2024-08-08 13:20:26
     */
    @Log("线下缴费")
    @PostMapping("peccancyChargeRecord/pay")
    @ResponseBody
    @RequiresPermissions("peccancyChargeRecord:charge")
    public FebsResponse updatePeccancyClause(@RequestBody PeccancyInformation peccancyInformation) throws FebsException {
        try {
            if(StringUtils.isBlank(peccancyInformation.getChargeUserId())){
                return new FebsResponse().fail().message("请选择收款人");
            }
            if(ObjectUtils.isEmpty(peccancyInformation.getChargeDate())){
                return new FebsResponse().fail().message("请选择收款时间");
            }
            if(StringUtils.isBlank(peccancyInformation.getChargeRemark())){
                return new FebsResponse().fail().message("请填写收款备注");
            }
            PeccancyInformation information = peccancyInformationService.findPeccancyInformationById(peccancyInformation.getInformationId());
            if(ObjectUtils.isEmpty(information)){
                return new FebsResponse().fail().message("未找到对应违章记录");
            }
            if(PeccancyConstant.INFORMATION_STATUS.UPLOAD.equals(information.getStatus())){
                return new FebsResponse().fail().message("该违章未提交，无法支付");
            }
            if(PeccancyConstant.IS_OR_NO.IS.equals(information.getPenaltyAmountStatus())){
                return new FebsResponse().fail().message("该违章已支付，无法再次支付");
            }
            peccancyInformation.setPenaltyAmountStatus(PeccancyConstant.IS_OR_NO.IS);
            peccancyInformation.setChargeType(PeccancyConstant.CHARGE_TYPE.OFFLINE);
            peccancyInformation.setUpdatedBy(getCurrentUser().getUserName());
            peccancyInformationService.informationOffLinePay(peccancyInformation);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "修改PeccancyClause失败";
            log.error(message, e);
            return failure(e,message);
        }
    }





}
